﻿using CubicFWNet.Application.SystemManager;
using CubicFWNet.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Newtonsoft.Json.Linq;
using CubicFWNet.Data.Models;
using CubicFWNet.Mvc.Models;
namespace CubicFWNet.Mvc.Controllers
{
    public class RoleController : ControllerBase
    {
        private RoleApp _app;
        private ModuleApp _moduleApp;
        public RoleController()
        {
            _app = new RoleApp();
            _moduleApp = new ModuleApp();
        }

        [Authenticate]
        [HttpGet]
        public  ViewResult Index()
        {
            return View(_app.Load());
        }

        [HttpGet]
        [HandlerAjaxOnly]
        public ActionResult GetFormJson(Guid id)
        {
            var data = _app.GetForm(id);
            return Content(data.ToJson());
        }

        [HttpPost]
        [HandlerAjaxOnly]
        public string Delete(Guid id)
        {
            try
            {
                _app.Delete(id);
            }
            catch (Exception e)
            {
                Result.Status = "error";
                Result.Message = e.Message;
            }
            return Result.ToJson();
        }

        //添加或修改角色
        [HttpPost]
        [HandlerAjaxOnly]
        public string Add(Role role, string moduleIds)
        {
            try
            {
                role.CreatorId = operatorModel.UserId;
                _app.AddOrUpdate(role, moduleIds.Split(','));
            }
            catch (Exception ex)
            {
                Result.Status = "error";
                Result.Message = ex.Message;
            }
            return Result.ToJson();
        }

        public ActionResult GetPermissionTree(Guid roleId)
        {
            var moduledata = _moduleApp.GetList();
            var authorizeModule = new List<Guid>();
            if (roleId != Guid.Empty)
            {
                authorizeModule = _app.Load(roleId);
            }
            var treeList = new List<TreeViewModel>();
            foreach (Module item in moduledata)
            {
                TreeViewModel tree = new TreeViewModel();
                bool hasChildren = moduledata.Count(t => t.ParentId == item.Id) == 0 ? false : true;
                tree.id = item.Id.ToString();
                tree.text = item.Name;
                tree.value = item.Id.ToString();
                tree.parentId = item.ParentId.ToString();
                tree.isexpand = true;
                tree.complete = true;
                tree.showcheck = true;
                tree.checkstate = authorizeModule.Count(t => t == item.Id);
                tree.hasChildren = true;
                tree.img = "";
                treeList.Add(tree);
            }
            return Content(treeList.TreeViewJson());
        }

    }
}